#include "Alerts.h";

#include "Water_Level.h";

extern LiquidCrystal     lcd;
extern PROGMEM const char *dosing_pumps_name_table[];
extern Water_Level water_level;

Alerts::Alerts(){
  pinMode(Alerts_Horn_Pin, OUTPUT);
  Alert_On = false;
}

void Alerts::Check_Alert(){
  if ( (Number_OF_Alerts + water_level.Is_There_Alerts() )  == 0 ){
    Turn_Horn_off();
  } else {
    Turn_Horn_on();
  }
}
byte Alerts::Get_Number_OF_Alerts(){
  return (Number_OF_Alerts + water_level.Is_There_Alerts() ) ;
}

byte Alerts::Get_Number_Of_Print_Line(){
  byte Alerts = Number_OF_Alerts + water_level.Get_Number_Of_Print_Alerts();
  if ( Alerts == 0 ) {
    return 1;
  } 
  else {
    return Alerts;
  }
}

byte Alerts::Clear_Alert(byte Line_Num){
  Print_Clear(false,Line_Num);
  Check_Alert();
  return Get_Number_Of_Print_Line();
}

void Alerts::Print(byte Line_Num){
  Print_Clear(true,Line_Num);
}

void Alerts::Set_Dosing_Pump_Alert(byte num_pump){
  Dosing_Pump_Alert[num_pump] = true; 
  ++Number_OF_Alerts;
}
  
void Alerts::Print_Clear(bool Print , byte Line_Num){
  if ( Number_OF_Alerts == 0  && (water_level.Is_There_Alerts() == 0) ) {
    strcpy_P(buffer, (char*)pgm_read_word(&(  gen_string_table[  NO_ALERTS_STRING ]     )));
    lcd.print(buffer );
  } 
  else {
    byte alert_num = 0;
    byte water_level_Line = 0;

    for ( byte i= 0 ; i < NUMBER_OF_DOSING_PUMPS ; ++i ){
      if ( Dosing_Pump_Alert[i] ){
        if ( alert_num == Line_Num){
          if ( Print ){
            strcpy_P(buffer, (char*)pgm_read_word(&(  dosing_pumps_name_table[  i ]     )));
            lcd.print(buffer );
          } 
          else {
            Dosing_Pump_Alert[i] = false;
            --Number_OF_Alerts;
          }
          return;
        }
        ++alert_num;
      }
    }


    for ( byte i= 0 ; i < water_level.Get_Number_Of_Print_Alerts()  ; ++i ){
      if ( alert_num == Line_Num){
        water_level.Print_Alerts(water_level_Line);
      }
      ++water_level_Line;
      ++alert_num;
    }
  }
}

void Alerts::Turn_Horn_on(){
  digitalWrite(Alerts_Horn_Pin, HIGH);   
  Alert_On = true; 
}

void Alerts::Turn_Horn_off(){
  digitalWrite(Alerts_Horn_Pin, LOW);  
  Alert_On = false;   
}

void Alerts::Check_Horn(){
  digitalWrite(Alerts_Horn_Pin, HIGH);  
  delay(1000);
  if(  Alert_On == false ){
    digitalWrite(Alerts_Horn_Pin, LOW);
  }   
}










